package com.hhf.rpc.core.retry.impl;

import com.github.rholder.retry.*;
import com.hhf.rpc.core.model.RpcResponse;
import com.hhf.rpc.core.retry.RetryStrategy;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @Author hhf
 * @Date 2024/10/20
 * @Description 固定时间重试策略
 */
@Slf4j
public class FixtedIntervalRetryStrategy implements RetryStrategy {
    @Override
    public RpcResponse doRetry(Callable<RpcResponse> callable) throws Exception {

        //1. 构建重试器
        Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder()
                .retryIfExceptionOfType(Exception.class)
                .withWaitStrategy(WaitStrategies.fixedWait(5L, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                .withRetryListener(new RetryListener() {
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
                        log.warn("开始第{}次重试", attempt.getAttemptNumber());
                    }
                })
                .build();

        //2.返回
        RpcResponse rpcResponse = retryer.call(callable);
        return rpcResponse;
    }
}
